package com.bridgeintelligent.tag.customer.service;

import com.alibaba.fastjson.JSON;
import com.bridgeintelligent.tag.customer.entity.AnalysisSetup;
import com.bridgeintelligent.tag.customer.entity.ExploreTemplate;
import com.bridgeintelligent.tag.customer.entity.Result;
import com.bridgeintelligent.tag.customer.entity.TemplatePage;
import com.bridgeintelligent.tag.customer.mapper.AnalysisCatalogMapper;
import com.bridgeintelligent.tag.customer.mapper.AnalysisQuerySetupMapper;
import com.bridgeintelligent.tag.customer.mapper.ExploreTemplateMapper;
import com.bridgeintelligent.tag.customer.pojo.Filter;
import com.bridgeintelligent.tag.customer.pojo.FilterGroup;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.bridgeintelligent.tag.webserver.system.entity.DimUseRecord;
import com.bridgeintelligent.tag.webserver.system.service.DimUseRecordService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 画像分析服务层接口实现
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
@Slf4j
public class ExploreTemplateServiceImpl implements IExploreTemplateService {

    private ExploreTemplateMapper templateMapper;

    private AnalysisQuerySetupMapper querySetupMapper;

    private AnalysisCatalogMapper catalogMapper;

    private IAnalysisQuerySetupService analysisQuerySetupService;

    private DimUseRecordService dimUseRecordService;

    /**
     * 新增画像分析
     * @param template
     */
    @Override
    public void addExploreTemplate(ExploreTemplate template) {
        User user = TagSecurityHelper.currentUser();
        template.setId(IDGenerator.gen())
                .setCtTime(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_1))
                .setUtTime(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_1))
                .setCtName(user.getUserId());
        //保存基础信息
        templateMapper.addExploreTemplate(template);
        //保存分析设置信息
        List<AnalysisSetup> setups = template.getSetups();
        if (!CollectionUtils.isEmpty(setups)){
            setups.forEach(e ->{
                e.setId(IDGenerator.gen());
                e.setTpId(template.getId());
                querySetupMapper.addQuerySetup(e);
            });
        }

        //保存使用的标签明细
        if (!StringUtils.isEmpty(template.getDimIds())){
            dimUseRecordService.addRecord(DimUseRecord.of().setId(template.getId()).setDataType("3").setDimId(template.getDimIds()).setCreateTime(DateHelper.currentDateTime()));
        }
    }




    /**
     * 校验画像分析名是否重复
     * @param id
     * @param alName
     * @return
     */
    @Override
    public boolean checkAlName(String id,String alName) {
        String name = templateMapper.checkName(alName);
        if (StringUtils.isEmpty(name)){
            return false;
        }else{
            if (!StringUtils.isEmpty(id) && StringUtils.equals(name,id)){
                return false;
            }
            return true;
        }
    }

    /**
     * 修改画像分析
     * @param template
     */
    @Override
    public void updateExploreTemplate(ExploreTemplate template) {
        template.setUtTime(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_1));
        templateMapper.updateExploreTemplate(template);

        analysisQuerySetupService.delByTpId(template.getId());
        //修改分析设置信息
        List<AnalysisSetup> setups = template.getSetups();
        if (!CollectionUtils.isEmpty(setups)){
            setups.forEach(e ->{
                e.setId(IDGenerator.gen());
                e.setTpId(template.getId());
                querySetupMapper.addQuerySetup(e);
            });
        }

        //保存使用的标签明细
        if (!StringUtils.isEmpty(template.getDimIds())){
            dimUseRecordService.addRecord(DimUseRecord.of().setId(template.getId()).setDataType("3").setDimId(template.getDimIds()).setCreateTime(DateHelper.currentDateTime()));
        }
    }


    /**
     * 删除画像分析
     * @param id
     */
    @Override
    public void delExploreTemplate(String id) {

        templateMapper.delExploreTemplate(id);
        querySetupMapper.delQuerySetupByTpId(id);
    }


    /**
     * 画像分析详情
     * @param id
     * @return
     */
    @Override
    public ExploreTemplate findExploreTemplate(String id) {
        ExploreTemplate exploreTemplate = templateMapper.findExploreTemplate(id);
        List<AnalysisSetup> setups = querySetupMapper.findQueryByTpId(id);
        exploreTemplate.setSetups(setups);

        if (!StringUtils.isEmpty(exploreTemplate.getAlQuery())){
            //筛选条件实体
            FilterGroup filterGroup = JSON.parseObject(exploreTemplate.getAlQuery(), FilterGroup.class);
            List<Filter> filters = getFilter(filterGroup, new ArrayList<>());
            exploreTemplate.setFilterList(filters);
        }
        return exploreTemplate;
    }

    public List<Filter> getFilter( FilterGroup filterGroup,List<Filter> list){
        if (filterGroup != null){
           if (!CollectionUtils.isEmpty(filterGroup.getFilters())){
               for (Filter filter:filterGroup.getFilters()) {
                   filter.setCnDateName(fetchCNDateName(filter));
                   list.add(filter);
               }
           }
           if (!CollectionUtils.isEmpty(filterGroup.getChildren())){
               for (FilterGroup filterGroup1:filterGroup.getChildren()) {
                   getFilter(filterGroup1,list);
               }
           }
        }
        return list;
    }

    private final static String CN_DATE_FORMAT = "当前月份%s";
    private static final String MONTH_FORMAT = "%s年%s月";
    private static final String zero = "0";

    private String fetchCNDateName(Filter filter) {
        if (filter.isTimeType()) {
            return zero.equals(filter.getDataDate()) ? String.format(CN_DATE_FORMAT, "") : String.format(CN_DATE_FORMAT, "-" + filter.getDataDate());
        } else {
            String year = StringUtils.substring(filter.getDataDate(), 0, 4);
            String month = StringUtils.substring(filter.getDataDate(), 4);
            return month.startsWith(zero) ? String.format(MONTH_FORMAT, year, month.substring(1)) : String.format(MONTH_FORMAT, year, month);
        }
    }


    /**
     * 分页画像分析列表
     * @param pageNumber
     * @param pageSize
     * @param startTime
     * @param endTime
     * @param alName
     * @return
     */
    @Override
    public Result pageList(Integer pageNumber, Integer pageSize,String startTime,String endTime, String alName) {

        pageNumber = pageNumber == null ? 1 : pageNumber;
        pageSize = pageSize == null ? 10 : pageSize;
        //获取当前用户的id
        User user = TagSecurityHelper.currentUser();
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<ExploreTemplate> list = templateMapper.findList(user.getUserId(),alName,startTime,endTime);
        if (!CollectionUtils.isEmpty(list)){
            list.forEach(e -> {
                List<AnalysisSetup> setups = querySetupMapper.findQueryByTpId(e.getId());
                e.setSetups(setups);
            });
        }
        TemplatePage<ExploreTemplate> templatePage = new TemplatePage<>();
        templatePage.setContent(list);
        templatePage.setTotalPages(page.getPages());
        templatePage.setTotalElements(page.getTotal());
        templatePage.setSize(page.getPageSize());
        templatePage.setRequestPager(pageNumber);
        return new Result(0, "查询成功",templatePage);
    }

}
